import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { getDynamicFonts } from '@/utils/fontUtils';
import { request } from '@/api/request';
import { getUserData } from '@/utils/userUtils';
import './MyBill.css';

// 账单记录类型定义
interface BillingRecord {
  id: number;
  amount: number;
  balance_after: number;
  description: string;
  reserve_id: string | null;
  payment_order_id: string | null;
  status: string;
  server_type: string;
  updated_at: string;
  created_at: string;
  type: string;
}

// API响应类型定义
interface BillingResponse {
  success: boolean;
  user_uuid: string;
  billing_records: BillingRecord[];
  pagination: {
    total: number;
    page: number;
    limit: number;
    pages: number;
  };
}

const MyBill: React.FC = () => {
  const { t, i18n } = useTranslation();
  const dynamicFonts = getDynamicFonts(i18n);

  // 状态管理
  const [isExpanded, setIsExpanded] = useState(false);
  const [billingRecords, setBillingRecords] = useState<BillingRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [pagination, setPagination] = useState({
    page: 1,
    limit: 5,
    total: 0,
    pages: 0
  });
  const [hasMore, setHasMore] = useState(false);

  // 用于无限滚动的refs
  const observerRef = useRef<IntersectionObserver | null>(null);
  const lastItemRef = useRef<HTMLDivElement | null>(null);

  // 获取账单数据的API函数
  const fetchBillingRecords = useCallback(async (page: number = 1, isLoadMore: boolean = false) => {
    const userData = getUserData();
    if (!userData || !userData.visitor_uuid) {
      setError('用户未登录');
      return;
    }

    try {
      if (isLoadMore) {
        setLoadingMore(true);
      } else {
        setLoading(true);
        setError(null);
      }

      const response = await request.get<BillingResponse>('/api/tokens/billing-records', {
        params: {
          page,
          limit: pagination.limit
        }
      });

      if (response.data.success) {
        const newRecords = response.data.billing_records;
        const newPagination = response.data.pagination;

        if (isLoadMore) {
          // 加载更多：追加到现有记录
          setBillingRecords(prev => [...prev, ...newRecords]);
        } else {
          // 首次加载：替换所有记录
          setBillingRecords(newRecords);
        }

        setPagination(newPagination);
        setHasMore(newPagination.page < newPagination.pages);
      } else {
        setError(t('settings.myBill.loadFailed'));
      }
    } catch (err) {
      // console.error('获取账单数据失败:', err);
      console.error('get billing records failed', err);
      setError(t('settings.myBill.loadFailed'));
    } finally {
      setLoading(false);
      setLoadingMore(false);
    }
  }, [pagination.limit, t]);

  // 加载更多数据
  const loadMore = useCallback(() => {
    if (!loadingMore && hasMore) {
      fetchBillingRecords(pagination.page + 1, true);
    }
  }, [fetchBillingRecords, loadingMore, hasMore, pagination.page]);

  // 无限滚动的Intersection Observer回调
  const handleIntersection = useCallback((entries: IntersectionObserverEntry[]) => {
    const [entry] = entries;
    if (entry.isIntersecting && hasMore && !loadingMore && !loading) {
      loadMore();
    }
  }, [hasMore, loadingMore, loading, loadMore]);

  // 设置Intersection Observer
  useEffect(() => {
    if (!isExpanded || !lastItemRef.current) return;

    observerRef.current = new IntersectionObserver(handleIntersection, {
      rootMargin: '100px', // 提前100px触发加载
      threshold: 0.1 // 当10%的元素可见时触发
    });

    if (lastItemRef.current) {
      observerRef.current.observe(lastItemRef.current);
    }

    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
    };
  }, [isExpanded, billingRecords.length, handleIntersection]);

  // 添加媒体查询，在移动端调整分页大小
  useEffect(() => {
    const handleResize = () => {
      const isMobile = window.innerWidth < 768;
      if (isMobile && pagination.limit !== 10) {
        setPagination(prev => ({ ...prev, limit: 10 }));
      } else if (!isMobile && pagination.limit !== 20) {
        setPagination(prev => ({ ...prev, limit: 20 }));
      }
    };

    handleResize(); // 初始化时执行一次
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [pagination.limit]);

  // 处理展开/收起
  const handleToggleExpanded = () => {
    if (!isExpanded) {
      // 首次展开时获取数据
      fetchBillingRecords(1, false);
    }
    setIsExpanded(!isExpanded);
  };

  // 格式化时间
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString(i18n.language, {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 格式化服务类型
  const formatServerType = (serverType: string) => {
    switch (serverType) {
      case 'text':
        return t('settings.myBill.textService');
      case 'voice':
        return t('settings.myBill.voiceService');
      case 'img':
        return t('settings.myBill.img');
      case 'subscription_grant':
        return t('settings.myBill.subscription_grant');
      case 'subscription':
        return t('settings.myBill.subscription');
      case 'purchase':
        return t('settings.myBill.purchase');
      case 'disposable':
        return t('settings.myBill.disposable');
      case 'promotional':
        return t('settings.myBill.promotional');
      default:
        return serverType;
    }
  };

  // 格式化状态
  const formatStatus = (status: string) => {
    switch (status) {
      case 'confirmed':
        return t('settings.myBill.confirmed');
      case 'canceled':
        return t('settings.myBill.canceled');
      case 'pending':
        return t('settings.myBill.pending');
      default:
        return status;
    }
  };

  // 格式化类型
  const formatType = (type: string) => {
    switch (type) {
      case 'reserve':
        return t('settings.myBill.reserve');
      default:
        return type;
    }
  };

  return (
    <div className="w-full relative bg-zinc-900 rounded-[10px] border border-[#282828] mx-auto mb-5 md:mb-10">
      <div className="w-full h-[0px] border-t border-[#363636]"></div>

      <div className="p-5 sm:p-7 flex flex-col sm:flex-row justify-between gap-[14px] sm:gap-[0px]">
        <div className="flex flex-col sm:flex-row justify-between sm:items-center">
          <div style={{ fontFamily: dynamicFonts.font1 }} className="text-white text-[14px] sm:text-[16px] font-medium leading-normal lg:my-0 my-2">
            {t('settings.myBill.title')}
          </div>
        </div>
        <div className="flex flex-col sm:flex-row justify-between sm:items-center">
          <div className="flex">
            <button
              className="relative flex justify-center w-full items-center rounded-[10px] text-neutral-400 text-[13px] sm:text-[14px] font-normal underline cursor-pointer hover:text-white transition-colors duration-200"
              onClick={handleToggleExpanded}
            >
              <div className="flex justify-center items-center">
                <div style={{ fontFamily: dynamicFonts.font2 }}>
                  {isExpanded ? t('settings.myBill.hideBill') : t('settings.myBill.viewBill')}
                </div>
              </div>
            </button>
          </div>
        </div>
      </div>

      {/* 展开的账单内容 */}
      {isExpanded && (
        <div className="px-4 sm:px-7 pb-5 sm:pb-7 bill-container">
          <div className="w-full border-t border-[#363636] mb-3 sm:mb-4"></div>

          {loading && (
            <div className="text-center py-3 sm:py-4">
              <div style={{ fontFamily: dynamicFonts.font2 }} className="text-neutral-400 text-[12px] sm:text-[14px] flex items-center justify-center">
                <div className="animate-spin mr-2 h-4 w-4 border-2 border-t-transparent border-neutral-400 rounded-full"></div>
                {t('settings.myBill.loading')}
              </div>
            </div>
          )}

          {error && (
            <div className="text-center py-3 sm:py-4">
              <div style={{ fontFamily: dynamicFonts.font2 }} className="text-red-400 text-[12px] sm:text-[14px]">
                {error}
              </div>
            </div>
          )}

          {!loading && !error && billingRecords.length === 0 && (
            <div className="text-center py-3 sm:py-4">
              <div style={{ fontFamily: dynamicFonts.font2 }} className="text-neutral-400 text-[12px] sm:text-[14px]">
                {t('settings.myBill.noRecords')}
              </div>
            </div>
          )}

          {!loading && !error && billingRecords.length > 0 && (
            <div className="space-y-2 sm:space-y-3 max-h-72 sm:max-h-96 overflow-y-auto custom-scrollbar rounded-md">
              {/* 表头 */}
              <div className="grid grid-cols-12 gap-2 pb-2 border-b border-[#363636] sticky top-0 bg-zinc-900 z-10 px-2 py-2 bill-header">
                <div style={{ fontFamily: dynamicFonts.font1 }} className="col-span-6 text-white text-[12px] md:text-[14px] font-medium text-left">
                  {t('settings.myBill.orderNumber')}
                </div>
                <div style={{ fontFamily: dynamicFonts.font1 }} className="col-span-2 text-white text-[12px] md:text-[14px] font-medium text-center">
                  {t('settings.myBill.amount')}
                </div>
                <div style={{ fontFamily: dynamicFonts.font1 }} className="col-span-2 text-white text-[12px] md:text-[14px] font-medium text-center">
                  {t('settings.myBill.balance')}
                </div>
                <div style={{ fontFamily: dynamicFonts.font1 }} className="col-span-2 text-white text-[12px] md:text-[14px] font-medium text-center">
                  {t('settings.myBill.time')}
                </div>
              </div>

              {/* 账单记录列表 */}
              {billingRecords.map((record, index) => (
                <div
                  key={record.id}
                  ref={index === billingRecords.length - 1 ? lastItemRef : null}
                  className="grid grid-cols-12 gap-2 py-2 px-2 border-b border-[#2a2a2a] last:border-b-0 hover:bg-zinc-800 transition-colors duration-200 bill-item"
                  style={{ animation: `fadeIn ${0.2 + index * 0.05}s ease-out forwards` }}
                >
                  {/* 第一列：订单号 */}
                  <div className="col-span-6 flex  items-center">
                    <div style={{ fontFamily: dynamicFonts.font2 }} className="text-neutral-300 text-[11px] md:text-[13px] break-all">
                      {record.server_type === 'promotional' ? record.payment_order_id : record.reserve_id}
                    </div>

                  </div>

                  {/* 第二列：金额 */}
                  <div className="col-span-2 flex flex-col justify-center items-center">
                    <div
                      style={{ fontFamily: dynamicFonts.font2 }}
                      className={`text-[12px] md:text-[14px] font-medium ${record.amount < 0 ? 'text-red-400' : 'text-green-400'} text-center`}
                    >
                      {record.amount > 0 ? '+' : ''}{record.amount}
                    </div>
                    <div style={{ fontFamily: dynamicFonts.font2 }} className="text-neutral-500 text-[10px] md:text-[12px] truncate" title={record.description}>
                      {formatServerType(record.server_type)}
                    </div>
                  </div>

                  {/* 第三列：余额 */}
                  <div className="col-span-2 flex flex-col justify-center items-center">
                    <div style={{ fontFamily: dynamicFonts.font2 }} className="text-neutral-300 text-[12px] md:text-[14px] text-center">
                      {record.balance_after}
                    </div>
                    <div style={{ fontFamily: dynamicFonts.font2 }} className="text-neutral-500 text-[10px] md:text-[12px] text-center">
                      {formatStatus(record.status)}
                    </div>
                  </div>

                  {/* 第四列：时间 */}
                  <div className="col-span-2 flex flex-col justify-center items-center">
                    <div style={{ fontFamily: dynamicFonts.font2 }} className="text-neutral-300 text-[11px] md:text-[13px] text-center">
                      {formatDate(record.created_at)}
                    </div>
                  </div>
                </div>
              ))}

              {/* 加载更多指示器 */}
              {loadingMore && (
                <div className="text-center py-2 sm:py-3">
                  <div style={{ fontFamily: dynamicFonts.font2 }} className="text-neutral-400 text-[12px] sm:text-[14px] flex items-center justify-center">
                    <div className="animate-spin mr-2 h-3 w-3 sm:h-4 sm:w-4 border-2 border-t-transparent border-neutral-400 rounded-full"></div>
                    {t('settings.myBill.loadMore')}...
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default MyBill; 